package com.zznj.xzjc.fragment.index;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxui.fragment.NewLazyFragment;
import com.zznj.xzjc.R;
import com.zznj.xzjc.activity.index.IndexWebActivity;
import com.zznj.xzjc.activity.index.zhishiku.ActivityZhiShiKuMain;
import com.zznj.xzjc.adapter.index.ZhiShiKuAdapter;
import com.zznj.xzjc.event.EventTag;
import com.zznj.xzjc.event.MessageEvent;
import com.zznj.xzjc.net.SharedHelper;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.net.entity.IndexNewXianSuoBean;
import com.zznj.xzjc.net.entity.LoginBean;
import com.zznj.xzjc.net.rxjava.HttpMethods;
import com.zznj.xzjc.net.subscribers.ProgressSubscriber;
import com.zznj.xzjc.net.subscribers.SubscriberOnNextListener;
import com.zznj.xzjc.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.FormBody;

import static com.zznj.xzjc.net.rxjava.HttpMethods.BASE_WORK_URL;

/**
 * 描述：知识库
 */
public class ZhiShiKuFragment extends NewLazyFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    @BindView(R.id.tishiImg)
    ImageView tishiImg;
    @BindView(R.id.bottomLinear)
    View bottomLinear;

    Unbinder unbinder;

    private String searchType;



    public static ZhiShiKuFragment getInstance(String searchType,String areaCode,String selfLevel) {
        ZhiShiKuFragment fragment = new ZhiShiKuFragment();
        fragment.searchType = searchType;
        if("RepositoryAllApi,LawSubject, PowerList".contains(searchType)){
            fragment.areaCode = areaCode;
            fragment.selfLevel = selfLevel;
        }
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.gyss_fragment_index_zxxs_layout;
    }

    private LoginBean user;
    private String areaCode;
    private String selfLevel;

    public void search(String areaCode, String selfLevel) {
        this.areaCode = areaCode;
        this.selfLevel = selfLevel+"";
        refresh(true);
    }

    private String Q_industryType_s_S;
    public void searchQ_industryType_s_S(String Q_industryType_s_S) {
        this.Q_industryType_s_S = Q_industryType_s_S;
        refresh(true);
    }

    private String Q_powerType_s_S;
    public void searchQ_powerType_s_S(String Q_powerType_s_S) {
        this.Q_powerType_s_S = Q_powerType_s_S;
        refresh(true);
    }

    private String Q_caseType_s_S;
    public void searchQ_caseType_s_S(String Q_caseType_s_S) {
        this.Q_caseType_s_S = Q_caseType_s_S;
        refresh(true);
    }

    private String Q_libType_s_S;
    private String Q_writType_s_S;
    public void searchAjlx(String Q_libType_s_S,String Q_writType_s_S, String Q_clueDomain_s_S) {
        this.Q_libType_s_S = Q_libType_s_S;
        this.Q_writType_s_S = Q_writType_s_S;
        this.Q_clueDomain_s_S = Q_clueDomain_s_S;
        refresh(true);
    }

    private String province;
    public void searchProvince(String province) {
        this.province = province;
        refresh(true);
    }

    private String Q_range_s_S;
    public void searchQ_range_s_S(String Q_range_s_S) {
        this.Q_range_s_S = Q_range_s_S;
        refresh(true);
    }

    private String Q_effectName_s_S;
    public void searchQ_effectName_s_S(String Q_effectName_s_S) {
        this.Q_effectName_s_S = Q_effectName_s_S;
        refresh(true);
    }

    private String Q_typeName_s_S;
    public void searchQ_typeName_s_S(String Q_typeName_s_S) {
        this.Q_typeName_s_S = Q_typeName_s_S;
        refresh(true);
    }

    private String Q_resourceType_s_S;
    public void searchQ_resourceType_s_S(String Q_resourceType_s_S) {
        this.Q_resourceType_s_S = Q_resourceType_s_S;
        refresh(true);
    }


    private String Q_clueDomain_s_S;
    public void searchQ_clueDomain_s_S(String Q_clueDomain_s_S) {
        this.Q_clueDomain_s_S = Q_clueDomain_s_S;
        refresh(true);
    }

    private String Q_orgType_s_S;
    public void searchQ_orgType_s_S(String Q_orgType_s_S) {
        this.Q_orgType_s_S = Q_orgType_s_S;
        refresh(true);
    }

    private String Q_year_s_N;
    public void searchQ_year_s_N(String Q_year_s_N) {
        this.Q_year_s_N = Q_year_s_N;
        refresh(true);
    }









    @Override
    protected void initView(View view) {
        unbinder = ButterKnife.bind(this, view);
        user = new Gson().fromJson(SharedHelper.readValueByKeyForString(mContext, "Member"), LoginBean.class);

        selfLevel = "true";


        init();
        initSrl();
        super.initView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if (messageEvent.getTag().equals(EventTag.DT)) {
            refresh(false);
        }
    }

    public void refresh(boolean isShowDialog) {
        isShowDialog = isShowDialog;
        page = 1;
        srlAll.setEnableLoadMore(true);
        mList.clear();
        bottomLinear.setVisibility(View.GONE);
        mAdapter.notifyDataSetChanged();
        getData();
    }


    private void initSrl() {
        srlAll.setEnableRefresh(true);
        srlAll.setEnableLoadMore(true);
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh(false);
        });
        srlAll.setOnLoadMoreListener(refresh_layout -> {
            isShowDialog = false;
            page++;
            getData();
        });
    }

    private List<IndexNewXianSuoBean> mList;
    private ZhiShiKuAdapter mAdapter;

    private void init() {
        mList = new ArrayList<>();
        ((SimpleItemAnimator) recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new ZhiShiKuAdapter(R.layout.gyss_item_zhishiku, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!isFirstLoad && type==-1){
            refresh(false);
        }
    }

    private int page = 1;
    private boolean isShowDialog = true;
    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        if(mList.size() == 0){
            page = 1;
        }
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if(srlAll != null){
                srlAll.finishLoadMore();
                srlAll.finishRefresh();
            }
            if (baseBean.isSuccess()) {
                String data = baseBean.getMessage();
                if (!StringUtils.isEmpty(data)) {
                    Map<String, String> dataMap = new Gson().fromJson(data, new TypeToken<Map<String, String>>() {
                    }.getType());
                    String solrDocumentList = dataMap.get("solrDocumentList");
                    if (!StringUtils.isEmpty(solrDocumentList)) {
                        if(page == 1){
                            mList.clear();
                        }
                        List<IndexNewXianSuoBean> sdList = new Gson().fromJson(solrDocumentList, new TypeToken<List<IndexNewXianSuoBean>>() {
                        }.getType());

                        if(mList.size() + sdList.size() > 0 && sdList.size() < 10){
                            bottomLinear.setVisibility(View.VISIBLE);
                            if(srlAll != null){
                                srlAll.setEnableLoadMore(false);
                            }
                        }

                        mAdapter.addData(sdList);
                    }
                }
            }
//            mAdapter.notifyDataSetChanged();
            mAdapter.setKey("");
            if(tishiImg != null){
                if(mAdapter.getItemCount() == 0){
                    tishiImg.setVisibility(View.VISIBLE);
                    srlAll.setVisibility(View.GONE);
                    if(!StringUtils.isEmpty("")){
                        tishiImg.setImageResource(R.mipmap.gyss_wjsjg_img);
                    }else{
                        tishiImg.setImageResource(R.mipmap.gyss_zwnr_img);
                    }
                }else{
                    tishiImg.setVisibility(View.GONE);
                    srlAll.setVisibility(View.VISIBLE);
                }
            }
        };
        Map<String, Object> paramsMap = new HashMap<>();

        if(!StringUtils.isEmpty(areaCode)){
            if("RepositoryAllApi,LawSubject, PowerList".contains(searchType)){
                paramsMap.put("Q_districtCode_s_S", areaCode);
                if(!StringUtils.isEmpty(selfLevel)){
                    paramsMap.put("selfLevel", selfLevel+"");
                }
            }
        }
        if(!StringUtils.isEmpty(Q_industryType_s_S)){
            paramsMap.put("Q_industryType_s_S", Q_industryType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_powerType_s_S)){
            paramsMap.put("Q_powerType_s_S", Q_powerType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_caseType_s_S)){
            paramsMap.put("Q_caseType_s_S", Q_caseType_s_S+"");
        }
        if(!StringUtils.isEmpty(province)){
            paramsMap.put("province", province+"");
        }else{
            if("ExpertLib".equals(searchType) || "CheckupOrg".equals(searchType)){
                paramsMap.put("province", "420000");
            }
        }
        if(!StringUtils.isEmpty(Q_libType_s_S)){
            paramsMap.put("Q_libType_s_S", Q_libType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_writType_s_S)){
            paramsMap.put("Q_writType_s_S", Q_writType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_clueDomain_s_S)){
            paramsMap.put("Q_clueDomain_s_S", Q_clueDomain_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_range_s_S)){
            paramsMap.put("Q_range_s_S", Q_range_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_effectName_s_S)){
            paramsMap.put("Q_effectName_s_S", Q_effectName_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_typeName_s_S)){
            paramsMap.put("Q_typeName_s_S", Q_typeName_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_resourceType_s_S)){
            paramsMap.put("Q_resourceType_s_S", Q_resourceType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_orgType_s_S)){
            paramsMap.put("Q_orgType_s_S", Q_orgType_s_S+"");
        }
        if(!StringUtils.isEmpty(Q_year_s_N)){
            paramsMap.put("Q_year_s_N", Q_year_s_N+"");
        }

        if("RepositoryAllApi,LawSubject, PowerList".contains(searchType)){
//            ((ActivityZhiShiKuMain)getActivity()).searchParam(paramsMap);
        }
        if("KnowledgeExample".equals(searchType)){
        }
        paramsMap.put("page",page+"");
        paramsMap.put("rows","10");
        String searchParam = new Gson().toJson(paramsMap);
        FormBody requestBody = new FormBody.Builder()
                .add("searchType", searchType)
                .add("searchParam", searchParam)
                .add("searchWord", "")
                .build();

        for (int i = 0; i < requestBody.size(); i++) {
            System.out.println("XXX请求参数：" + requestBody.name(i) + ":" + requestBody.value(i));
        }

        HttpMethods.getInstance().getFindXianSuoList(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    private int type = -1;
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        String infoSign = "";
        type = 0;
        IndexNewXianSuoBean item = mList.get(position);
//        Bundle bundle = new Bundle();
//        bundle.putString("id",item.getId_l()+"");
        String titleInfo = "";
        if(item.getDataType_i().equals("1")){
            //案例库
            titleInfo = "案例库详情";
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailAlk.class,bundle);
        }else if(item.getDataType_i().equals("2")){
            titleInfo = "法律法规详情";
            //法律法规
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailFlfg.class,bundle);
        }else if(item.getDataType_i().equals("4")){
            titleInfo = "科技文献库详情";
            //科技文献库
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailKjwx.class,bundle);
        }else if(item.getDataType_i().equals("5")){
            titleInfo = "专家库详情";
            //专家库
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailZjk.class,bundle);
        }else if(item.getDataType_i().equals("6")){
            titleInfo = "鉴定机构库详情";
            //鉴定机构库
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailJdjg.class,bundle);
        }else if(item.getDataType_i().equals("14")){
            titleInfo = "权力清单详情";
            //权力清单
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailQlqd.class,bundle);
        }else if(item.getDataType_i().equals("13")){
            titleInfo = "执法主体详情";
            //执法主体
//            RxActivityTool.skipActivity(mContext, ActivityZhiShiKuDetailZfzt.class,bundle);
        }


        Bundle bundle = new Bundle();
        bundle.putString("path", BASE_WORK_URL+item.getId_l()+"&userId="+user.getUserId());
        bundle.putString("title", "知识库详情");

        bundle.putString("contentTitle", item.getIndexTitle_s());
        bundle.putString("collectType", "knowledgeLib");
        bundle.putString("infoSign", item.getDataType_i());
        bundle.putString("id", item.getId_l()+"");
        bundle.putString("fromActivity","1");

        RxActivityTool.skipActivity(mContext, IndexWebActivity.class,bundle);

    }
}